import { useState } from 'react';
import clsx from 'clsx';
import FAQ_ITEMS from '../../data/faq';

import styles from './styles.module.css';
import { useRef } from 'react';

type FaqItemProps = {
  question: string;
  answer: string;
};

function FaqItem({ question, answer }: FaqItemProps) {
  const [isOpen, setIsOpen] = useState(false);
  const contentRef = useRef<HTMLDivElement>(null);

  return (
    <div
      className={clsx(styles.faqItem, isOpen && styles.open)}
      style={{ cursor: 'pointer' }}
    >
      <div
        className={styles.faqQuestion}
        onClick={() => setIsOpen((prev) => !prev)}
      >
        {question}
        <svg
          className={styles.arrowIcon}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          style={{
            transition: 'transform 0.5s',
            transform: isOpen ? 'rotate(90deg)' : 'rotate(0deg)',
          }}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
        </svg>
      </div>
      <div
        ref={contentRef}
        className={styles.faqAnswer}
        style={{
          maxHeight: isOpen
            ? contentRef.current
              ? `${contentRef.current.scrollHeight}px`
              : '1000px'
            : '0px',
          overflow: 'hidden',
          transition: 'max-height 0.5s cubic-bezier(0.4, 0, 0.2, 1)',
        }}
        aria-hidden={!isOpen}
      >
        <div dangerouslySetInnerHTML={{ __html: answer }} />
      </div>
    </div>
  );
}

export default function Faq() {
  return (
    <section>
      <div className={styles.faqContainer}>
        {FAQ_ITEMS?.map((item, index) => (
          <FaqItem key={index} {...item} />
        ))}
      </div>
    </section>
  );
}
